using System;
using System.Collections.Generic;
using System.Text;

using System.Data;
using System.Data.SqlClient;

namespace DataAccessLayer
{

    public class LabelGateway
    {
        private SqlConnection connection;
        private SqlCommand command;
        private SqlDataAdapter adapter;
        private SqlCommandBuilder builder;

        public LabelGateway(SqlConnection connection)
        {
            this.connection = connection;
            command = new SqlCommand("SELECT * FROM Label WHERE id=@id", connection);
            command.Parameters.Add("@id", SqlDbType.BigInt);

            adapter = new SqlDataAdapter(command);
            builder = new SqlCommandBuilder(adapter);

        }

        public long Insert(string labelName, RecordingDataSet recordingDataSet)
        {
            RecordingDataSet.LabelRow newLabel = recordingDataSet.Label.NewLabelRow();
            newLabel.id = IdGenerator.GetNextId(recordingDataSet.Label.TableName, connection);
            newLabel.name = labelName;
            recordingDataSet.Label.AddLabelRow(newLabel);
            Update(recordingDataSet);
            return newLabel.id;
        }

        public RecordingDataSet.LabelRow FindById(long id, RecordingDataSet recordingDataSet)
        {
            command.Parameters["@id"].Value = id;
            adapter.Fill(recordingDataSet, recordingDataSet.Label.TableName);

            DataRow[] rows = recordingDataSet.Label.Select(String.Format("id={0}", id));

            if (rows.Length < 1) return null;
            return (RecordingDataSet.LabelRow)rows[0];
        }

        public void Delete(long deletedId, RecordingDataSet recordingDataSet)
        {
            RecordingDataSet.LabelRow deletedRow = FindById(deletedId, recordingDataSet);
            deletedRow.Delete();
            Update(recordingDataSet);
        }

        public void Update(RecordingDataSet recordingDataSet)
        {
            adapter.Update(recordingDataSet, recordingDataSet.Label.TableName);
        }



    }
}
